#!/usr/bin/bash
pro_base="$(cd `dirname $(readlink -f $0)`;pwd)"        # program base directory. readlink是为了获取脚本的真实路径
pro_root="${pro_base##*/}"                              # 我的程序的根目录名字.   readlink使得ln创建的软链也能正确地执行
pro_name="$(readlink -f $0 | sed 's#^.*/##; s#.sh$##')" # 删除'/'前的路径,删除'.sh'

source ${pro_base}/shared/include.sh || exit 1
Include ${pro_base}/${pro_name}/${pro_name}.conf ${pro_base}/${pro_name}/{usage,core}.sh
Include ${pro_base}/shared/prompt.sh

Help "$@"
[[ $# -lt 1 ]] && Usage && exit 1
if [[ $1 == "-i" ]]; then
    fnInstallDependence
    exit
fi
! [[ -f "$1" ]] && PError "[缺失'主机清单'文件]: $1" && exit 1

# 设置pipefail，当所有管道命令都成功时才返回0
# 若不设置pipefail，则返回码为管道最后一个命令的返回码
set -o pipefail

[[ -d ${log_dir} ]] || Eval_exit "mkdir -p ${log_dir}"
> ${stdout_log}                                         # 大括号中的命令在subshell中运行
{
for i in `egrep -av $'^[ \t]{0,}#|^[ \t]{0,}$' "$1"`    # 将注释行和空白行去掉
do
    if [[ `echo $i |awk -F, '{print NF}'` != 5 ]]; then
        PError "[文件内容不规范] 请修改'$1'的内容:\n\t${i}"
        exit 1                                          # subshell中的exit命令仅退出subshell,父shell命令将继续运行
    fi
done

# telnet to all the hosts
Eval_exit "check_host_port '$1'"

# add mapping for IP and hostname to /etc/hosts
Eval_exit "fnHostCheck '$1'"


# generate ssh keys
#Eval_exit "cd /root"                                   # 不能切换目录,否则下面的"CopyKey '$1'"会出错
#Eval_exit "rm -rf .ssh/id_rsa*"
#key_generate=0
if [[ -f $HOME/.ssh/id_rsa && -f $HOME/.ssh/id_rsa.pub ]]; then
    read -p"用户'$USER'已存在SSH私钥,是否要生成新的SSH私钥? (y/n 默认:n) " a
    case $a in
        y|Y|yes|YES)
            key_generate=1;
            ;;
        *)
            key_generate=0;
            ;;
    esac
else
    key_generate=1;
fi

if [[ ${key_generate} -eq 1 ]]; then
    Eval_exit "expect '${pro_base}/${pro_name}/02ssh-keygen.exp'"
    POk "keys for ssh are generated..."
fi
# copy ssh key to remote host(s)
Eval_exit "fnCopyKey '$1'"
echo "******************************"
} |& tee -a ${stdout_log}

[[ $? -ne 0 ]] && exit 1            # 为使管道中的Eval_exit执行失败时,不仅仅退出subshell,要求当前shell也退出

PInfo "目标远程主机共有 `egrep -acv $'^[ \t]{0,}#|^[ \t]{0,}$' $1` 台"   # egrep -acv $'^[ \t]{0,}#|^[ \t]{0,}$' $1 中间的'$'不能省略
PInfo "密钥成功添加到 `grep -ac 'Number of key(s) added: 1' ${stdout_log}` 台远程主机上.接下来检查能否免密登陆到远程主机"

#Eval_exit "grep -a 'hostname;pwd;date' /etc/hosts"                      # 'hostname;pwd;date'是在 HostCheck 函数中定义的
fnSshHosts $1                           # 检查是否能够免密连接远程主机;若密钥添加失败,会有类似这样的提示root@127.0.0.1's password:
